import { IJson, IResAndReqFieldsMap } from "../../interface/type"
import utilTool from "../../util/tool"
import { vbenConfig } from '../../vbenConfig'

let funArr: string[] // 操作方法数组
let htmlArr: string[]
let exportFunArr: string []
let apiArrs: string []
let toolHtmlArr: string []

function handleOpts(pageConfig: IJson, apiPramAndRes: IResAndReqFieldsMap) {
  funArr = [] // 操作方法数组
  htmlArr = []
  exportFunArr = []
  apiArrs = []
  toolHtmlArr = []

  pageConfig?.opts?.forEach((it: IJson) => {
    if (it.confrimMsg) {
      htmlArr.push(`
      {
        // icon: 'ant-design:delete-outlined',
        ${it.text === '删除' ? "color: 'error'," : ""}
        label: '${it.text}',
        popConfirm: {
          title: '${it.confrimMsg}',
          confirm: handle${utilTool.firstUp(it.apiName)}.bind(null, record)
        }
      }
      `)
    } else {
      htmlArr.push(`
      {
        // icon: 'ant-design:delete-outlined',
        label: '${it.text}',
        onClick: handle${utilTool.firstUp(it.apiName)}.bind(null, record)
      }
      `)
    }

    const apiRes = apiPramAndRes[it.apiName]
    const param: string [] = []
    console.log('--------it.apiName---------', it.apiName)
    console.log('apiRes >>>>>>>>>>>>>>>>', JSON.stringify(apiRes))
    apiRes.request.forEach(item => {
      if (item.name !== 'orgId') {
        param.push(`${item.name}: record.${item.name},
      `)
      }
    })

    exportFunArr.push(`handle${utilTool.firstUp(it.apiName)}`)
    apiArrs.push(it.apiName)

    funArr.push(`
      async function handle${utilTool.firstUp(it.apiName)}(record: Recordable) {
        await ${it.apiName}({ ${param.join('')} });
        createMessage.success('${it.text}成功！');
        // console.log(record);
        reload();
      }
    `)

  })

  // ----------------------------处理编辑和导入导出------------------------------------------------

  if (pageConfig.modify?.apiName) {
    toolHtmlArr.push(`<Button type="primary" @click="handleCreate"> 新增 </Button>
    `)
    funArr.push(`
      function handleCreate() {
        openDrawer(true, {
          isUpdate: false,
        });
      }
    `)
    exportFunArr.push('handleCreate')
  }

  if (!!pageConfig.modify?.fileName) {
    funArr.push(`
      function handleEdit(record: Recordable) {
        openDrawer(true, {
          record,
          isUpdate: true,
        });
      }
    `)

    htmlArr.unshift(`
    {
      // icon: 'clarity:note-edit-line',
      label: '编辑',
      onClick: handleEdit.bind(null, record)
    }`)

    exportFunArr.push('handleEdit')
  }

  if (pageConfig.list?.exportFile?.apiName) {
    toolHtmlArr.push(`<Button type="primary" :loading='exportLoading' @click="handleExportFile" > 导出  <Icon icon= 'bx:bx-download'></Icon></Button>
    `)

    funArr.push(`
      // 导出
      async function handleExportFile() {
        if (exportLoading.value) {
          return;
        }
        exportLoading.value = true;
        try {
          let obj = getForm().getFieldsValue();
          await ${pageConfig.list?.exportFile?.apiName}(obj);
        } finally {
          exportLoading.value = false;
        }
      }
    `)
    exportFunArr.push('handleExportFile')
  }

}

export function getNoEditTemp (): string {
  return ``
}

// 数据模板
export function listTemp(apiPramAndRes: IResAndReqFieldsMap, pageConfig: IJson) {
  // console.log('json: ', json)
  if (!pageConfig.list.fileName) {
    return ''
  }
  // 是否有编辑文件
  const hasEditFile = !!pageConfig.modify?.fileName ? true : false

  // 根据规则生成操作按钮、方法
  handleOpts(pageConfig, apiPramAndRes)
  const apiFileName = pageConfig.filePath ? pageConfig.filePath : vbenConfig.baseUrl.replace(/\//g, '')
  const modifyName = pageConfig.modify?.fileName ? utilTool.firstUp(pageConfig.modify.fileName) : 'Modify'

  return `<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        ${toolHtmlArr.join('')}
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            ${htmlArr.join(',')}
          ]"
        />
      </template>
    </BasicTable>
    `
    +
    (hasEditFile ? `
        <${modifyName}Drawer @register="registerDrawer" @success="handleSuccess" />
    ` : ``)
    +
    `
  </div>
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { ${pageConfig.list.apiName}, ${apiArrs.join(', ')} } from '/@/api/${vbenConfig.modelName}/${apiFileName}';
  `
  +
  (hasEditFile ?`
  import { useDrawer } from '/@/components/Drawer';
  import ${modifyName}Drawer from './${modifyName}Drawer.vue';
  ` : ``)
  +
  `
  import { Button } from '/@/components/Button';
  import { tableConfig } from './${pageConfig.list.fileName}.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { Icon } from '/@/components/Icon';

  export default defineComponent({
    name: '${pageConfig.list.fileName}Management',
    components: { BasicTable, ${ hasEditFile ? (modifyName + 'Drawer,') : ''} TableAction, Button },
    setup() {
      const { createMessage } = useMessage();
      ${!!pageConfig.list?.exportFile?.apiName ? 'const exportLoading = ref(true)' : ''}
      `
      +
      (hasEditFile ? `const [registerDrawer, { openDrawer }] = useDrawer();` : ``)
      +
      `
      const [registerTable, { reload ${!!pageConfig.list?.exportFile?.apiName ? ', getForm' : ''} }] = useTable(Object.assign({
        api: ${pageConfig.list.apiName},
        actionColumn: {
          width: ${htmlArr.length * 65},
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      },
      tableConfig.call(this)));

      function handleSuccess() {
        reload();
      }

      ${funArr.join('')}

      return {
        registerTable,
        registerDrawer,
        handleSuccess,
        ${exportFunArr.join(',')}
      };
    },
  });
</script>
`
}
